package mypodsync;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

import mypodsync.service.Service;
import mypodsync.service.ServiceManager;

import org.jdesktop.jdic.tray.SystemTray;
import org.jdesktop.jdic.tray.TrayIcon;

public class MyPodSyncControl {
    
    private TrayIcon trayIcon;
    private MyPodSyncFrame frame;
    private List<Config> configs;
    private Logger log = Logger.getLogger(MyPodSyncControl.class.getName());
    private ServiceManager serviceMan;
    private GeneralConfig generalConfig;
    
    public MyPodSyncControl() {
    }
    
    void exit() {
        System.exit(0);
    }
    
    void savePrefs() {
        for (Config conf : configs) {
            conf.save();
        }
    }
    
    void openPrefs() {
        for (Config conf : configs) {
            conf.load();
        }
        frame.pack();
        frame.setVisible(true);
        frame.setExtendedState(JFrame.NORMAL);
    }
    
    void executeAll() {
        for (Service service : serviceMan.getServices()) {
            service.execute();
        }
    }
    
    private void initPrefs() {
        configs = new ArrayList<Config>();
        generalConfig.load();
        configs.add(generalConfig);
        frame.addTab(generalConfig.getTitle(), generalConfig.getUI());
        List<Service> services = serviceMan.getServices();
        for (Service serv : services) {
            Config conf = serv.getConfig();
            conf.load();
            configs.add(conf);
            frame.addTab(conf.getTitle(), conf.getUI());
        }
    }

    public void start() {
        log.info("Starting");
        generalConfig = new GeneralConfig();
        generalConfig.load();
        serviceMan = new ServiceManager(generalConfig);
        frame = new MyPodSyncFrame();
        ImageIcon icon = new ImageIcon(getClass().getResource("/icon_plain.png"));
        frame.setIconImage(icon.getImage());
        frame.setController(this);
        SystemTray systemTray = SystemTray.getDefaultSystemTray();
        trayIcon = new TrayIcon(icon, "MyPodSync", frame.getPopupMenuTray());
        trayIcon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                openPrefs();
            }
        });
        systemTray.addTrayIcon(trayIcon);
        initPrefs();
    }
}

